<script setup lang="ts">
import { onMounted } from 'vue';
import { tableConfig } from './config/table-config';
import { doGetBomDetail } from '@/api/modeling/bom/index';
import { generateNameToLevel } from '@/config/constant';
import type { BomParams } from '@/api/modeling/bom/model/type';

const tableData = ref();
const tableRef = ref();
const $route = useRoute();

/**
 * 获取 BOM 明细数据
 */
const getBomDetailData = async (query: BomParams) => {
    try {
        const { id, materialCode } = query;
        if (id == null && materialCode == null) {
            throw new Error('页面发生错误，id 不存在！');
        }
        const { data } = await doGetBomDetail(query); // 获取 BOM 详情

        if (data) {
            const { materialCode, materialName, children, id } = data || {};
            const BomChildren = children || [];
            tableData.value = [
                {
                    level: 0,
                    parentMaterialCode: materialCode,
                    parentMaterialName: materialName,
                    unitUsage: 1,
                    id
                },
                ...BomChildren
            ];
        }

        tableRef.value.setTableData(tableData.value);
    } catch (error) {
        console.error(error);
    }
};

onMounted(() => {
    getBomDetailData($route.query);
});
</script>

<template>
    <q-page>
        <base-table
            :id="generateNameToLevel('4')"
            ref="tableRef"
            :tableConfig="tableConfig"
            :show-setting="true"
            :show-page="false"
            :un-action="true"
            :table-attr="{ treeProps: { children: 'children' }, rowKey: 'id' }"
        >
        </base-table>
    </q-page>
</template>

<style lang="scss" scoped></style>
